<template>
    <van-nav-bar title="商品类目" left-text="返回" left-arrow @click-left="onClickLeft" />  
    <!--商品分类详情-->
    <!--activeId 右侧选中项的ID   activeIndex左侧的索引值-->
    <van-tree-select
      v-model:active-id="rightactiveId"
      v-model:main-active-index="leftactiveIndex"
      :items="cateGoryData"
    >
    <template #content>
    <van-grid :gutter="10" :column-num="3" icon-size="50px">
      <van-grid-item v-for="item in cateGoryData[leftactiveIndex]?.children" 
      :key="item.id" 
      :icon="item.img" 
      :text="item.text"
      :to="({name:'movelist',query:{categoryId:item.id}})" />
    </van-grid>
    </template>
    </van-tree-select>


</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { CategoryApi } from '@/api';

//右侧id
const rightactiveId = ref(1);
//左侧索引
const leftactiveIndex = ref(0);
const cateGoryData = ref([
     {
        text: '浙江',
        children: [
            { text: '杭州', id: 1 ,img:'https://m.360buyimg.com/babel/jfs/t1/215072/20/30644/9019/646da7a1F63613a8c/a5b2428860e14917.jpg'},
            { text: '温州', id: 2 ,img:'https://m.360buyimg.com/babel/jfs/t1/100342/15/41391/10528/646dad13F717b6cd9/a301d60c251994d8.jpg'},
            { text: '宁波', id: 3, disabled: true },
        ],
    },
])
//后台返回的数据
const cateGoryData2 = ref([
    { id: 1, name: '手机', img: '', parentId: 0 },
    { id: 2, name: 'oppo手机', img: '', parentId: 1 },   
    { id: 3, name: '华为手机', img: '', parentId: 1 },   
    { id: 4, name: '家用电器', img: '', parentId: 0 },   
    { id: 5, name: '电饼档', img: '', parentId: 4 },   
    { id: 6, name: '炒菜锅', img: '', parentId: 4 },      
])

onMounted(() => { 
    cateGoryData2.value.forEach((item: any) => { 
        item.text = item.name
    })
    console.log(cateGoryData2);
    let cateGoryData3 = cateGoryData2.value.reduce((newArray: any, currValue: any) => { 
        currValue.children = cateGoryData2.value.filter(
            item=> { return item.parentId === currValue.id })
    if (currValue.parentId === 0) { 
        newArray.push(currValue)
    }
    return newArray
    }, [])
    console.log("cateGoryData3==", cateGoryData3)
    cateGoryData.value = cateGoryData3
    getCategroyApi()
})
//获取后台数据
const getCategroyApi = () => { 
    CategoryApi.select.call().then((res: any) => { 
        console.log(res);
         res.forEach((item: any) => {
            item.text = item.name
        })
    
        let cateGoryData3 = res.reduce((newArray: any, currValue: any) => {
            currValue.children = res.filter(
                (item:any) => { return item.parentId === currValue.id })
            if (currValue.parentId === 0) {
                newArray.push(currValue)
            }
            return newArray
        }, [])
        console.log("cateGoryData3==", cateGoryData3)
        cateGoryData.value = cateGoryData3
    })
}

const onClickLeft = () => history.back();
</script>